package com.wash.shoes.handler;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.wash.shoes.context.DataPermissionContext;
import com.wash.shoes.mapper.UserShopMapper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 门店数据权限处理器
 */
@Component
public class DeptDataPermissionHandler implements DataPermissionHandler {
    @Autowired
    private TokenService tokenService;
    // @Autowired

    @Override
    public String handle(DataPermissionContext.DataPermissionInfo dataPermissionInfo) {
        // 获取当前用户所属部门ID
        // 这里假设通过SecurityUtils获取当前用户信息
        // 实际项目中请替换为你的用户信息获取方式

        ServletRequestAttributes servletRequestAttributes =
            ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes());

        SysUser user = SecurityUtils.getLoginUser().getUser();
        user.getRoles();
        // TODO 通过os_user_shop表关联查询 获取当前用户关联的类型
        /*    if () {
        
        }*/

        UserShopMapper userShopMapper = SpringUtils.getBean(UserShopMapper.class);
        // 用户账号绑定的类型
        List<String> userBindType = userShopMapper.getUserBindType(String.valueOf(user.getUserId()));
        if (Objects.nonNull(userBindType) && userBindType.size() > 1) {
            throw new RuntimeException("账号绑定的类型不唯一.请检查");
        }
        // TODO 判断是走的哪一个类型,根据不同的类型去查询不同的字段,比如订单表 工厂类型的时候就需要按工厂id去查询,门店类型的时候就需要按门店id去查询
        List<Object> shopIds = tokenService.getUserShopId(servletRequestAttributes.getRequest());
        if (CollectionUtil.isEmpty(shopIds)) {
            return null;
        }

        String field = dataPermissionInfo.getField();
        String tableAlias = dataPermissionInfo.getTableAlias();

        // 构建字段名
        String fieldName = tableAlias.isEmpty() ? field : tableAlias + "." + field;
        StringBuilder stringBuilder = new StringBuilder();
        for (Object shopId : shopIds) {
            stringBuilder.append("'").append(shopId).append("'").append(",");
        }
        if (stringBuilder.length() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        // 返回部门数据权限SQL
        // return fieldName + " in ( " + stringBuilder.toString() + ")";//现在是在mybatis 里面去进行动态过滤的没有使用这个
        return "";
    }

    @Override
    public String getType() {
        return "order";
    }
}